﻿using System;
using System.Collections.Generic;
using System.Text;
using ExtensionLoader;
using HttpServer;
using HttpServer.Templates;
using CableBeachMessages;

namespace WorldServer.Extensions
{
    public class WebFrontend : IExtension<WorldServer>
    {
        const string TEMPLATE_FOLDER = WorldServer.DATA_DIR + "webcontent/";
        const string WELCOME_SPLASH_PAGE = TEMPLATE_FOLDER + "welcomesplashpage.tpl";

        WorldServer server;

        public WebFrontend()
        {
        }

        public bool Start(WorldServer server)
        {
            this.server = server;

            // Login webpage HEAD request, used to check if the login webpage is alive
            server.HttpServer.AddHandler("HEAD", null, "^/$", LoginWebpageHeadHandler);

            // Login webpage GET request, gets the login webpage data (purely aesthetic)
            server.HttpServer.AddHandler("GET", null, @"^/(\?.*)?$", LoginWebpageGetHandler);

            return true;
        }

        public void Stop()
        {
        }

        void LoginWebpageHeadHandler(IHttpClientContext client, IHttpRequest request, IHttpResponse response)
        {
        }

        void LoginWebpageGetHandler(IHttpClientContext client, IHttpRequest request, IHttpResponse response)
        {
            string output = String.Empty;
            Dictionary<string, object> variables = new Dictionary<string, object>();

            try
            {
                output = server.HttpTemplates.Render(WELCOME_SPLASH_PAGE, variables);
                byte[] data = Encoding.UTF8.GetBytes(output);
                response.ContentLength = data.Length;
                response.ContentType = "text/html";
                response.Body.Write(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                Logger.Error("Failed to render " + WELCOME_SPLASH_PAGE + " template: " + ex.Message);
            }
        }
    }
}
